<template>
  <div>
    <unit-table
      ref="unitTable"
      :columns="this.$staticMenu.needsColumns"
      :params="tableParams"
      :size="pageSize"
      selectType="checkbox"
      :sizeOptions="pageSizeOptions"
      :type="tableType"
      :url="tableUrl"
      rowKeyName="id"
      :rowSelection="rowSelection"
      @onSelect="tableOnSelect"
    >
      <!-- 补充搜索条件 -->
      <a-row slot="searchCri">
        <a-col :span="3">
          <a-select
            class="searchCriteria"
            @change="handleNeedChange"
            v-model="tableParams.classify"
          >
            <a-select-option value="">
              全部需求分类
            </a-select-option>
            <a-select-option value="生产需求">
              生产需求
            </a-select-option>
            <a-select-option value="评估需求">
              评估需求
            </a-select-option>
            <a-select-option value="意见反馈">
              意见反馈
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="5">
          <a-input
            v-model="tableParams.name"
            class="searchCriteria"
            placeholder="需求名称（仅支持数字、字母和汉字）"
            @keydown.native="keydown($event)"
            onkeyup="value=value.replace(/[\s+`~!@#$%^&*()_\-+=<>?:{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、 ]/,'') "
            onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/^[a-zA-Z0-9_()（）\u4e00-\u9fa5]{1,50}$/,''))"
          />
        </a-col>
        <!--       <a-col :span="5">-->
        <!--         <a-input v-model="tableParams.name" class="searchCriteria" placeholder="需求名称（仅支持数字、字母和汉字）" onkeyup="value=value.replace(/[\s+`~!@#$%^&*()_\-+=<>?:{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、 ]/,'') " onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/^[a-zA-Z0-9_()（）\u4e00-\u9fa5]{1,50}$/,''))" />-->
        <!--       </a-col>-->
        <a-col :span="3">
          <a-input
            v-model="tableParams.people"
            class="searchCriteria"
            placeholder="上报人"
          />
        </a-col>
        <a-col :span="2" style="line-height:32px;text-align: right;">
          需求截止日期:&nbsp;&nbsp;
        </a-col>
        <a-col :span="3">
          <a-range-picker v-model="time" @change="handleDateChange" />
        </a-col>
        <a-col :span="2" style="line-height:32px;text-align: right;">
          上报时间:&nbsp;&nbsp;
        </a-col>
        <a-col :span="3">
          <a-range-picker
            v-model="timeReport"
            @change="handleDateReportChange"
          />
        </a-col>
        <a-col :span="3" style="text-align: right;">
          <a-button type="primary" @click="criteriaSearch">
            <a-icon type="search" />
            查询
          </a-button>
          <a-button @click="clearCriteria">
            <a-icon type="sync" />
            重置
          </a-button>
        </a-col>
      </a-row>
      <!-- end -->
      <!-- 补充表格操作 -->
      <div slot="tableAct" class="actionBtn">
        <!--      <a-button  type="primary" @click="addNeeds">-->
        <!--        <a-icon type="plus"/>-->
        <!--        新增需求-->
        <!--       </a-button>-->
        <a-button v-if="this.isManager" type="primary" @click="acceptAll">
          <a-icon type="check" />
          审批通过
        </a-button>
        <a-button v-if="this.isManager" type="danger" @click="rejectAll">
          <a-icon type="close" />
          拒绝
        </a-button>
      </div>
      <!-- end -->
      <span slot="departmentName" slot-scope="props">
        <a-tooltip placement="top">
          <template slot="title">
            <span>{{ props.record.demandDes }}</span>
          </template>
          <span class="ellipsis">{{ props.record.demandDes }}</span>
        </a-tooltip>
      </span>
      <span slot="demandName" slot-scope="props">
        <a-tooltip placement="top">
          <template slot="title">
            <span>{{ props.record.demandName }}</span>
          </template>
          <span class="ellipsis">{{ props.record.demandName }}</span>
        </a-tooltip>
      </span>
      <span slot="statusSwitch" slot-scope="props">
        <span v-if="props.record.status == '审批通过'" class="text-success">
          {{ props.record.status }}
        </span>
        <span v-if="props.record.status == '审批拒绝'" class="text-danger">
          {{ props.record.status }}
        </span>
        <span v-if="props.record.status == '未审批'">
          {{ props.record.status }}
        </span>
      </span>
      <!-- 补充表格每行的操作 -->
      <span slot="tableRowAct" slot-scope="props">
        <a>
          <span class="ant-tag" @click="downloadData(props.record)">
            <a-icon type="download" /> 下载
          </span>
        </a>
        <!--        <a-divider type="vertical" v-if="props.record.status=='审批通过'" />
        <a v-if="props.record.status=='审批通过'">
          <span class="ant-tag ant-tag-green" @click="addHost(props.record)">
            <a-icon type="plus"/> 创建
          </span>
        </a>-->
      </span>
    </unit-table>
    <modal
      ref="taskModalForm"
      :demandClassify="demandclassify"
      :demandId="id"
      :demandName="name"
      :demandYear="demandyear"
      :tabType="tabType"
      :title="modalTitle"
      :visible="modalVisible"
      @cancel="handleCancel"
      @ok="handleOk"
    >
    </modal>
    <reaModal
      :title="reaModalTitle"
      :visible="reaModalVisible"
      :record="curVal"
      @ok="handleReaOk"
      @cancel="handleReaCancel"
    ></reaModal>
    <rejModal
      :title="rejModalTitle"
      :visible="rejModalVisible"
      :record="curVal"
      @ok="handleRejOk"
      @cancel="handleRejCancel"
    ></rejModal>
  </div>
</template>

<script>
import { GETNEEDLIST, NEEDACCEPT, NEEDREJECT } from "@/../static/js/apis.js";
import unitTable from "@/common/tableCheck";
import global from "@/../static/global.vue";
import modal from "./taskModal";
import moment from "moment";
import reaModal from "./acereasonModal";
import rejModal from "./rejreasonModal";
export default {
  inject: ["reload"], //注入App里的reload方法
  name: "allUnit",
  components: {
    unitTable,
    modal,
    reaModal,
    rejModal
  },

  computed: {
    //  判断是否管理员
    isManager() {
      return global.isManager(global.SYS_BUSINSESS_MANAGE);
      //  return localStorage.getItem('role').indexOf('0') > -1
    },
    rowSelection() {
      return {
        selectedRowKeys: this.tableSelectedKeys || [], // 选中行的key当props传值过来时，默认选中
        selectedRows: [], // 选中行的内容
        onChange: (selectedRowKeys, selectedRows) => {
          this.rowSelection.selectedRowKeys = selectedRowKeys;
          this.rowSelection.selectedRows = selectedRows;
          this.tableOnSelect(selectedRowKeys, selectedRows);
        },
        getCheckboxProps: record => ({
          props: {
            disabled: record.status !== "未审批" // Column configuration not to be checked
          }
        })
      };
    }
  },
  data() {
    return {
      tableSelectedKeys: [],
      tableUrl: GETNEEDLIST.url, //调用表格组件，必须参数，后台数据接口
      tableType: GETNEEDLIST.type, //调用表格组件，必须参数，后台方法方法（get，post）
      pageSize: 15,
      pageSizeOptions: ["15", "20", "40"],
      /*modal参数*/
      modalTitle: "", //modal标题
      modalVisible: false, //modal关闭打开控制器
      /*调用表格组件，可选参数，其他相关搜索条件*/
      tableParams: {
        classify: "",
        name: "",
        people: "",
        starttime: "",
        endtime: "",
        td_start: "",
        td_end: ""
      },
      time: [],
      timeReport: [],
      userRole: localStorage.getItem("role"),
      name: "",
      id: "",
      demandyear: "",
      demandclassify: "",
      tabType: "",
      str: "",
      reaModalVisible: false,
      reaModalTitle: "",
      curVal: "",
      rejModalVisible: false,
      rejModalTitle: ""
    };
  },
  mounted() {
    if (this.$route.query.type === "JRXQ") {
      this.tableParams.starttime = this.getNowFormatDate();
      this.time = [
        moment(this.getNowFormatDate(), "YYYY/MM/DD"),
        moment(this.getNowFormatDate(), "YYYY/MM/DD")
      ];
      this.tableParams.endtime = this.getNowFormatDate();
      this.criteriaSearch();
    } else if (this.$route.query.type === "JRXF") {
      this.tableParams.td_start = this.getNowFormatDate();
      this.tableParams.td_end = this.getNowFormatDate();
      this.timeReport = [
        moment(this.getNowFormatDate(), "YYYY/MM/DD"),
        moment(this.getNowFormatDate(), "YYYY/MM/DD")
      ];
      this.criteriaSearch();
    }
  },
  methods: {
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    // getVal(msg){
    //   this.str = msg;
    //   console.log("msg"+this.str)
    // },
    /*modal确定事件*/
    handleOk(e) {
      this.modalVisible = false;
    },
    handleReaOk(e) {
      this.reaModalVisible = false;
    },
    /* modal取消事件 */
    handleReaCancel(e) {
      this.reaModalVisible = false;
    },
    handleRejOk(e) {
      this.rejModalVisible = false;
    },
    /* modal取消事件 */
    handleRejCancel(e) {
      this.rejModalVisible = false;
    },
    /*表格checkbox选中事件*/
    tableOnSelect(selectedRowKeys, selectedRows) {
      this.tableSelectedKeys = selectedRowKeys;
    },
    /*查询按钮*/
    criteriaSearch() {
      this.$refs.unitTable.fetch(1);
    },
    /*重置按钮*/
    clearCriteria() {
      this.tableParams.classify = "";
      this.tableParams.name = "";
      this.tableParams.people = "";
      this.tableParams.starttime = "";
      this.tableParams.endtime = "";
      this.time = [];
      this.tableParams.td_start = "";
      this.tableParams.td_end = "";
      this.timeReport = [];
      this.$refs.unitTable.rowSelection.onChange([], []);
      this.criteriaSearch();
    },
    getNowFormatDate() {
      var date = new Date();
      var seperator1 = "-";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },

    /*选择当前状态*/
    handleNeedChange(value) {
      this.tableParams.classify = value;
    },
    handleDateChange(date, dateString) {
      this.tableParams.starttime = dateString[0];
      this.tableParams.endtime = dateString[1];
      console.log(this.time);
    },
    handleDateReportChange(date, dateString) {
      this.tableParams.td_start = dateString[0];
      this.tableParams.td_end = dateString[1];
    },
    addNeeds() {
      this.$router.push({
        path: "/needsReport",
        query: { system: "业务管理" }
      });
    },
    acceptAll() {
      let self = this;
      const selectedRowKeys = self.tableSelectedKeys;
      var params = {
        ids: selectedRowKeys,
        userid: parseInt(localStorage.getItem("userid"))
      };
      self.curVal = params;
      if (selectedRowKeys.length <= 0) {
        self.$message.warning("请在表格中勾选要审批的数据！");
      } else {
        self.reaModalTitle = "原因";
        self.reaModalVisible = true;
      }
      // if (selectedRowKeys.length > 0) {
      //   NEEDACCEPT(params, function (res) {
      //     self.$message.success(res.message)
      //     self.reload()
      //
      //   })
      // } else {
      //   self.$message.warning("请在表格中勾选要审批的数据！")
      // }
    },
    rejectAll() {
      // let self = this
      // const selectedRowKeys = self.tableSelectedKeys
      // var params = {
      //   ids: selectedRowKeys,
      //   userid: parseInt(localStorage.getItem("userid"))
      // }
      // if (selectedRowKeys.length > 0) {
      //   NEEDREJECT(params, function (res) {
      //     self.$message.success(res.message)
      //     self.reload()
      //
      //   })
      // } else {
      //   self.$message.warning("请在表格中勾选要审批的数据！")
      // }
      let self = this;
      const selectedRowKeys = self.tableSelectedKeys;
      var params = {
        ids: selectedRowKeys,
        userid: parseInt(localStorage.getItem("userid"))
      };
      self.curVal = params;
      if (selectedRowKeys.length <= 0) {
        self.$message.warning("请在表格中勾选要审批的数据！");
      } else {
        self.rejModalTitle = "原因";
        self.rejModalVisible = true;
      }
    },
    addHost(record) {
      this.modalTitle = "添加任务";
      this.name = record.demandName;
      this.id = record.id;
      this.demandyear = record.endtime;
      this.demandclassify = record.demandClassify;
      this.modalVisible = true;
      this.creator = record.creator;

      console.log(record);
      if (record.demandClassify === "生产需求") {
        this.tabType = "1";
        this.showTab = true;
      } else {
        this.tabType = "2";
        this.showTab = false;
      }
    },
    /*modal取消事件*/
    handleCancel(e) {
      this.modalVisible = false;
    },
    downloadData(record) {
      let id = record.id;
      window.open(global.bussinessManUrl + "/demandsubmit/download?id=" + id);
    }
    // // 只能输入汉字、英文、数字
    // btKeyDown(e) {
    //   e.target.value = e.target.value.replace(/^[a-zA-Z0-9_()（）\u4e00-\u9fa5]{1,50}$/,"");
    // },
    // //限制输入特殊字符
    // btKeyUp(e) {
    //   e.target.value = e.target.value.replace(/[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/,"");
    // }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.searchCriteria {
  width: 90%;
}

.actionBtn button:not(:last-child),
.ant-row button:not(:last-child) {
  margin-right: 20px;
}
</style>
